package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.domain.SQuestion;
import com.zhentao.dto.SingleChoiceQuestion;
import com.zhentao.dto.WordReturn;
import com.zhentao.service.SQuestionService;
import com.zhentao.utils.WordService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class FileWordServiceImpl {
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.upload.name}")
    private String url;
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Resource
    private SQuestionService sQuestionService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    public void UploadQuestion(MultipartFile file) {
        String s = UUID.randomUUID() + file.getOriginalFilename().
                substring(file.getOriginalFilename().lastIndexOf("."));

        File file1 = new File(uploadFolder, s);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String replace = staticAccessPath.replace("**", "");
        System.out.println(file1);


        //测试文件
        String filename = String.valueOf(file1);
        String textContent = null;
        try {
            textContent = WordService.readDoc(filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
		System.out.println(textContent);
        List<SingleChoiceQuestion> questions = parseSingleChoiceQuestions(textContent);
        for (SingleChoiceQuestion question : questions) {
            String[] split = question.getStem().split("\n");
            if (split.length>1) {
                String aa="";
                int dotIndex = split[0].indexOf('.');
                if (dotIndex != -1) {
                    String afterDot = split[0].substring(dotIndex + 1);
                   aa+=afterDot;
                } else {
                    aa=split[0];
                    System.out.println("没有找到`.`分隔符");
                }

                String s1 = split[1];
                String s2 = split[2];
                String s3 = split[3];
                String s4 = split[4];
                aa+="/"+s1+"_"+s2+"_"+s3+"_"+s4;
                int jishu=0;// 假设初始值为0，表示符合条件的字符数量
                String[] split1 = question.getAnswer().split("[、.]");

                for (String s5 : split1) {
                    if (s5.length() == 1 && s5.matches("[ABCD]")) {
                        jishu++;
                    }
                }
                if (jishu==1) {
                    SQuestion sQuestion = new SQuestion();
                    sQuestion.setQuestion(aa);
                    String[] split2 = question.getAnswer().split("[.]");
                    if (split2.length==0){
                        sQuestion.setAnswerTxt(question.getAnswer());
                    }else {
                        sQuestion.setAnswerTxt(split2[0]);
                    }
                    sQuestion.setTypeId(1);
//                    sQuestionService.save(sQuestion);
                    redisTemplate.opsForZSet().add(file.getOriginalFilename(), sQuestion, new Date().getTime());

                }else {
                    SQuestion sQuestion = new SQuestion();
                    sQuestion.setQuestion(aa);
                    String[] split2 = question.getAnswer().split("[、]");
                    StringBuilder aaa= new StringBuilder();
                    for (String s5 : split2) {
                        aaa.append(s5);
                    }
                    sQuestion.setAnswerTxt(String.valueOf(aaa));
                    sQuestion.setTypeId(2);
//                    sQuestionService.save(sQuestion);
                    redisTemplate.opsForZSet().add(file.getOriginalFilename(), sQuestion, new Date().getTime());
                }

            }else {
                if (question.getAnswer().equals("正确")||question.getAnswer().equals("错误")||question.getAnswer().equals("对")||question.getAnswer().equals("错")){
                    SQuestion sQuestion = new SQuestion();
                    String aa="";
                    int dotIndex =question.getStem().indexOf('.');
                    if (dotIndex != -1) {
                        String afterDot = question.getStem().substring(dotIndex + 1);
                        aa+=afterDot;
                    } else {
                        aa=question.getStem();
                        System.out.println("没有找到`.`分隔符");
                    }
                    sQuestion.setQuestion(aa);
                    sQuestion.setAnswerTxt(question.getAnswer());
                    sQuestion.setTypeId(3);
//                    sQuestionService.save(sQuestion);
                    redisTemplate.opsForZSet().add(file.getOriginalFilename(), sQuestion, new Date().getTime());
                }else {
                    SQuestion sQuestion = new SQuestion();
                    String aa="";
                    int dotIndex =question.getStem().indexOf('.');
                    if (dotIndex != -1) {
                        String afterDot = question.getStem().substring(dotIndex + 1);
                        aa+=afterDot;
                    } else {
                        aa=question.getStem();
                        System.out.println("没有找到`.`分隔符");
                    }
                    sQuestion.setQuestion(aa);
                    sQuestion.setAnswerTxt(question.getAnswer());
                    sQuestion.setTypeId(4);
//                    sQuestionService.save(sQuestion);
                    redisTemplate.opsForZSet().add(file.getOriginalFilename(), sQuestion, new Date().getTime());
                }
            }

        }
    }

    public static List<SingleChoiceQuestion> parseSingleChoiceQuestions(String content) {
        List<SingleChoiceQuestion> questions = new ArrayList<>();
        StringBuilder stemBuilder = new StringBuilder();

        for (String line : content.split("\n")) {
            String trimmedLine = line.trim();

            // 检查是否遇到答案标记
            boolean isAnswerLine = trimmedLine.startsWith("答案：") || trimmedLine.startsWith("答案:") || trimmedLine.startsWith("答：") || trimmedLine.startsWith("答:");

            if (isAnswerLine) {
                // 如果遇到答案标记，则之前的所有内容都是题干
                String stem = stemBuilder.toString().trim();
                if (!stem.isEmpty()) { // 确保题干不为空
                    // 提取答案部分，这里我们假设答案紧跟在标记之后，可能有空格或其他字符作为分隔
                    // 但由于我们不知道确切的分隔符，我们简单地尝试从冒号或全角冒号之后提取
                    int startIndex = Math.max(trimmedLine.indexOf('：'), trimmedLine.indexOf(':'));
                    if (startIndex != -1) {
                        String answer = trimmedLine.substring(startIndex + 1).trim(); // 从冒号或全角冒号之后提取答案
                        questions.add(new SingleChoiceQuestion(stem, answer));
                    } else {
                        // 如果没有找到冒号或全角冒号，则可能整行都是答案（这种情况可能不太常见）
                        // 注意：这可能会引入错误，因为如果没有明确的分隔符，就很难确定答案的结束位置
                        questions.add(new SingleChoiceQuestion(stem, trimmedLine.trim()));
                    }
                }
                // 重置题干构建器
                stemBuilder = new StringBuilder();
            } else {
                // 否则，将当前行添加到题干构建器中
                if (stemBuilder.length() > 0) {
                    stemBuilder.append("\n");
                }
                stemBuilder.append(trimmedLine);
            }
        }

        // 注意：如果最后一个问题是没有答案的（即文件以题干结束），则它不会被添加到列表中
        // 如果这是不希望的，您可能需要添加额外的逻辑来处理这种情况

        return questions;
    }

    //将reids放到mysql当中
    public WordReturn redisToMysql(String fileName, Integer subId){
        int zhengque = 0;
        int cuowu = 0;
        Set<Object> quesion =  redisTemplate.opsForZSet().range(fileName, 0, new Date().getTime()); // 假设-1表示获取所有元素
        List<SQuestion> list = sQuestionService.list(Wrappers.<SQuestion>lambdaQuery().eq(SQuestion::getSubId, subId));

// 创建一个HashMap来存储list中的question到SQuestion的映射
        Map<String, SQuestion> questionMap = list.stream().collect(Collectors.toMap(SQuestion::getQuestion, Function.identity()));

        for (Object q : quesion) {
            SQuestion q1= (SQuestion) q;
            SQuestion dbQuestion = questionMap.get(q1.getQuestion());
            if (dbQuestion != null) {
                // 如果在list中找到了相同的question，则认为是错误（或视业务需求而定）
                cuowu++;
            } else {
                // 如果没有在list中找到，则认为是新的或正确的（需要保存并增加正确计数）
                q1.setSubId(subId);
                sQuestionService.save(q1);
                zhengque++;
            }
        }

        redisTemplate.delete(fileName);
        return new WordReturn("", zhengque, cuowu);
    }
}
